<?php

namespace PolarisbackEndFrameRe\router;

/**
 * 路由
 * @author TINUOKAS1/Astoflow
 */

class Router {
    private $routes = [];

    public function add($route, $controller) {
        $this->routes[$route] = $controller;
    }

    public function dispatch($url) {
        foreach ($this->routes as $pattern => $controller) {
            if (preg_match('#^' . $pattern . '$#', $url, $matches)) {
                array_shift($matches); // Remove the full match
                $controllerMethod = explode('@', $controller);
                $controllerClass = $controllerMethod[0];
                $method = $controllerMethod[1];

                $controllerInstance = new $controllerClass();
                call_user_func_array([$controllerInstance, $method], $matches);
                return;
            }
        }
        echo "404 Not Found";
    }

    public function loadRoutesFromFiles($directory) {
        $files = glob($directory . '/*.php');
        foreach ($files as $file) {
            $this->parseFileForRoutes($file);
        }
    }

    private function parseFileForRoutes($file) {
        $content = file_get_contents($file);
        preg_match_all('/\/\*\*\s*@Controller\s+(\w+)\s*\*\/\s*function\s+(\w+)\s*\(/', $content, $matches, PREG_SET_ORDER);
        foreach ($matches as $match) {
            $controllerName = $match[1];
            $methodName = $match[2];
            $route = '/' . strtolower($controllerName) . '/' . strtolower($methodName);
            $this->add($route, $controllerName . '@' . $methodName);
        }
    }
}